package com.zyw.zhuangdian.controller;

import com.alibaba.fastjson.JSONObject;
import com.zyw.zhuangdian.constant.ServiceConstant;
import com.zyw.zhuangdian.pojo.Resp;
import com.zyw.zhuangdian.pojo.dto.UserDto;
import com.zyw.zhuangdian.pojo.in.UserDtoIn;
import com.zyw.zhuangdian.pojo.out.UserDtoOut;
import com.zyw.zhuangdian.property.MyProperties;
import com.zyw.zhuangdian.service.CacheService;
import com.zyw.zhuangdian.service.UserService;
import com.zyw.zhuangdian.util.Assert;
import com.zyw.zhuangdian.util.BeanConvertUtil;
import com.zyw.zhuangdian.util.RespUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping(value = "/admin")
@RequiredArgsConstructor
@Slf4j
public class AdminController {
    private final UserService userService;
    private final CacheService cacheService;
    private final MyProperties properties;

    /**
     * 列出普通用户
     * @param json
     * @return
     */
    @RequestMapping(value = "/listUsers", method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> listUsers(@RequestBody JSONObject json) {
        UserDtoIn in = BeanConvertUtil.covertBean(json, UserDtoIn.class);
        in.setPrivilege(ServiceConstant.PRIVILEGE_NORMAL);
        Resp<List<UserDtoOut>> resp = userService.listUsers(in);
        if (resp.getTotal()>0){
            resp.getData().forEach(UserDto::harmless);
        }
        return RespUtil.OK(resp);
    }

    /**
     * 列出管理员
     * @param json
     * @return
     */
    @RequestMapping(value = "/listAdministrators", method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> listAdministrators(@RequestBody JSONObject json) {
        UserDtoIn in = BeanConvertUtil.covertBean(json, UserDtoIn.class);
        in.setPrivilege(ServiceConstant.PRIVILEGE_ADMINISTRATOR);
        Resp<List<UserDtoOut>> resp = userService.listUsers(in);
        if (resp.getTotal()>0){
            resp.getData().forEach(UserDto::harmless);
        }
        return RespUtil.OK(resp);
    }

    /**
     * 重置用户密码
     * @param json
     * @return
     */
    @RequestMapping(value = "/resetUserPassword", method = RequestMethod.POST)
    public ResponseEntity<Resp<?>> resetUserPassword(@RequestBody JSONObject json) {
        Assert.hasKey(json,"uid","用户id不能为空");

        UserDtoIn in = BeanConvertUtil.covertBean(json, UserDtoIn.class);
        in.setPassword("123456");
        Resp<Void> resp = userService.updateUser(in);
        return RespUtil.OK(resp);
    }


}
